package com.zhoug.commonlib2.notifycation;

import android.app.Notification;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;

import com.zhoug.logger2.Logger;

import androidx.annotation.Nullable;

/**
 * @Author: zhoug
 * @Date: 2024-11-16
 * @Description:
 */
public class MyForeService extends Service {
    private static final String TAG = ">>>MyService";
    private static boolean isStart = false;

    public static void start(Context context) {
        if (!isStart) {
            Intent intent = new Intent(context, MyForeService.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(intent);
            } else {
                context.startService(intent);
            }
        } else {
            Logger.d(TAG, "start:服务已启动");
        }
    }

    public static void stop(Context context) {
        Intent intent = new Intent(context, MyForeService.class);
        context.stopService(intent);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Logger.d(TAG, "onCreate:创建服务");
        isStart = true;

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Logger.d(TAG, "onStartCommand:");
        WarningRingHelper  mWarningRingHelper = WarningRingHelper.getInstance();
        if (!mWarningRingHelper.isPlaying()) {
            mWarningRingHelper.startAlarm(this);
        }

        WarningNotificationHelper warningNotificationHelper = new WarningNotificationHelper();
        Notification notification = warningNotificationHelper.createNotification();
        startForeground(1001, notification);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForeground(true);
        isStart = false;
        WarningRingHelper.getInstance().stopAlarm();
        Logger.d(TAG, "onDestroy:服务已关闭");
    }


}
